package com.cmes.core.utils;

/**
 * IP地址转换
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
public class IpUtils {

    /**
     * IP4 转换为长整型
     *
     * @param ipAddress IP地址
     * @return LONG
     */
    public static long parseIP4Address(String ipAddress) {
        if (StringUtils.isEmpty(ipAddress)) {
            return 0;
        }
        ipAddress = ipAddress.trim();
        if (StringUtils.isEmpty(ipAddress) ||
                ipAddress.startsWith(StringPool.DOT) ||
                ipAddress.endsWith(StringPool.DOT)) {
            return 0L;
        }
        String[] ipAry = StringUtils.split(ipAddress, StringPool.DOT);
        if (ipAry.length != 4) {
            return 0L;
        }
        try {
            long ipLong = 0;
            int shift = 3;
            for (String ip : ipAry) {
                long segment = Long.parseLong(ip);
                ipLong += segment << ((shift--) * 8);
            }
            return ipLong;
        } catch (Exception e) {
            // 转换失败，不做处理
        }
        return 0L;
    }

}
